using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace SqlTools.SchemaReader.UI
{
	public partial class Relationships : Form
	{
		protected Database _database = null;

		public Relationships()
		{
			InitializeComponent();
		}

		public Database Database
		{
			get { return _database; }
			set { _database = value; }
		}

		public void LoadRelationships()
		{
			if ( _database == null )
				return;

			Stack<Table> referenceList;

			foreach ( Table table in _database.Tables )
			{
				TreeNode node = new TreeNode(table.Name);
				tvwTables.Nodes.Add(node);

				referenceList = new Stack<Table>();

				referenceList.Push(table);

				LoadRelationships(table, referenceList, node);
			}
		}

		protected void LoadRelationships(Table table, Stack<Table> refList, TreeNode parentNode)
		{
			foreach ( ForeignKey fk in table.ForeignKeys )
			{
				if ( fk.ReferenceTable == fk.ForeignKeyTable )
				{
					// skip self referencing foreign keys
					continue;
				}
				else if ( fk.ForeignKeyTable == table )
				{
					// don't want any infinite loops
					if ( refList.Contains(fk.ReferenceTable) )
						continue;

					TreeNode node = new TreeNode(fk.ReferenceTable.Name);
					parentNode.Nodes.Add(node);

					Stack<Table> newList = new Stack<Table>();
					Table[] tables = refList.ToArray();

					foreach ( Table stable in tables )
					{
						newList.Push(stable);
					}

					newList.Push(fk.ReferenceTable);
					LoadRelationships(fk.ReferenceTable, newList, node);
				}
				else if ( fk.ReferenceTable == table )
				{
					// don't want any infinite loops
					if ( refList.Contains(fk.ForeignKeyTable) )
						continue;

					TreeNode node = new TreeNode(fk.ForeignKeyTable.Name);
					parentNode.Nodes.Add(node);

					Stack<Table> newList = new Stack<Table>();
					Table[] tables = refList.ToArray();

					foreach ( Table stable in tables )
					{
						newList.Push(stable);
					}

					newList.Push(fk.ForeignKeyTable);
					LoadRelationships(fk.ForeignKeyTable, newList, node);
				}
			}
		}
	}
}